package com.sdy.dcsb.web.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.sdy.common.model.Response;
import com.sdy.dcsb.biz.model.EsbApp;
import com.sdy.dcsb.biz.model.EsbServiceAtomDeploy;
import com.sdy.dcsb.biz.model.EsbServiceAtomDeployJoint;
import com.sdy.dcsb.biz.service.*;
import com.sdy.mvc.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;
import static org.springframework.util.StringUtils.isEmpty;

/**
 * <p>
 * 原子服务和标准服务部署表 前端控制器
 * </p>
 *
 * @author fb
 * @since 2019-09-29
 */
@Slf4j
@Controller
@RequestMapping("/EsbServiceAtomDeploy")
@Api(tags = "部署信息相关接口")
public class EsbServiceAtomDeployController extends BaseController {
    @Autowired
    private EsbServiceAtomDeployService esbServiceAtomDeployService;
    @Autowired
    private EsbAppService esbAppService;
    @Autowired
    private UserOperationLogService userOperationLogService;
    @Autowired
    private EsbInboundMainService esbInboundMainService;
    @Autowired
    private EsbAtomServiceService esbAtomServiceService;

    /**
     * 查询此条服务的服务部署信息
     * @param serviceid 标准服务id
     * @param deploytype 部署类别：0:部署的是标准服务,1:部署的是原子服务
     * @return
     */
    @GetMapping("/select")
    @ResponseBody
    @ApiOperation("查询此条服务的服务部署信息")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "serviceid", value = "标准服务id"),
            @ApiImplicitParam(dataType = "Integer", name = "deploytype", value = "部署类别：0:部署的是标准服务,1:部署的是原子服务"),
    })
    public Response select(Integer serviceid, Integer deploytype) {
        if(isEmpty(serviceid)) {
            return Response.error("服务id或原子服务id不能为空");
        }
        String applicationType = "app";
        if(deploytype == 1) {
            applicationType = "subapp";
        }else if(deploytype == 0) {
            applicationType = "app";
        }else if(isEmpty(deploytype)) {
            return Response.error("部署类别不能为空");
        }
        QueryWrapper<EsbApp> wrapper = new QueryWrapper<>();
        wrapper.likeRight("appname",applicationType);
        wrapper.orderByAsc("appname");
        List<EsbApp> result = esbAppService.list(wrapper);
        List<EsbServiceAtomDeployJoint> esbServiceAtomDeployJointResult = esbServiceAtomDeployService.findAppList(serviceid, deploytype);
        JSONArray array = new JSONArray();
        for (int i=0; i<result.size(); i++) {
            JSONObject object = new JSONObject();
            Integer count = 0;
            for (int j=0; j<esbServiceAtomDeployJointResult.size(); j++) {
                if(result.get(i).getAppname().equals(esbServiceAtomDeployJointResult.get(j).getInstancename())) {
                    object.put("app",esbServiceAtomDeployJointResult.get(j).getInstancename());
                    object.put("status",esbServiceAtomDeployJointResult.get(j).getStatus());
                    object.put("appStatus",esbServiceAtomDeployJointResult.get(j).getAppStatus());
                    object.put("type","1");
                    array.add(i,object);
                    count++;
                }
            }
            if(count == 0) {
                object.put("app",result.get(i).getAppname());
                object.put("status","0");
                object.put("appStatus",result.get(i).getStatus());
                object.put("type","0");
                array.add(i,object);
            }
        }
        return Response.success(array);
    }

    /**
     * 新增或修改服务或原子服务部署信息
     * @param map json形式
     * @return
     */
    @PostMapping("/update")
    @ResponseBody
    @ApiOperation("新增或修改服务或原子服务部署信息，0：修改服务，1：修改原子服务")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Map<String,Object>", name = "map", value = "例如：{\n" +
                    "\t\"deploytype\": 0,\n" +
                    "\t\"serviceid\": 300,\n" +
                    "\t\"data\": /EsbServiceAtomDeploy/select接口返回的json数组data里的内容\n" +
                    "}"),

    })
    public Response update(HttpServletRequest request, @RequestBody Map<String, Object> map) {
        Integer deploytype = null;
        Integer serviceid = null;
        try{
            deploytype = (Integer) map.get("deploytype");
            serviceid = (Integer) map.get("serviceid");
        }catch (Exception e) {
            return Response.error("请求的map有误");
        }
        JSONArray array = JSONArray.parseArray(JSONObject.toJSONString(map.get("data")));
        Integer count = 0;
        for(int i=0; i<array.size(); i++) {
            String type = JSONObject.parseObject(array.get(i).toString()).get("type").toString();
            String app = JSONObject.parseObject(array.get(i).toString()).get("app").toString();
            String appStatus = JSONObject.parseObject(array.get(i).toString()).get("appStatus").toString();
            String status = JSONObject.parseObject(array.get(i).toString()).get("status").toString();
            if(type.equals("1")) {
                EsbServiceAtomDeploy esbServiceAtomDeploy = new EsbServiceAtomDeploy();
                List<EsbServiceAtomDeploy> esbServiceAtomDeployResult = esbServiceAtomDeployService.list(new QueryWrapper<EsbServiceAtomDeploy>().
                        eq("serviceid", serviceid).eq("instancename",app));
                if(esbServiceAtomDeployResult.size() == 0) {
                    return Response.error("请求信息传入有误");
                }
                String statusLast = esbServiceAtomDeployResult.get(0).getStatus();
                if(!statusLast.equals(status)) {
                    esbServiceAtomDeploy.setStatus(status);
                    esbServiceAtomDeploy.setLastupdateTime(new Date());
                    if(deploytype == 1) {
                        userOperationLogService.savaUserLog(request, "修改原子服务部署信息："+
                                esbAtomServiceService.selectById(serviceid).getAtomserviceCode() + " ，app：" + app);
                    }else {
                        userOperationLogService.savaUserLog(request, "修改服务部署信息："+
                                esbInboundMainService.getById(serviceid).getServcode() + " ，app：" + app);
                    }
                    esbServiceAtomDeployService.update(esbServiceAtomDeploy,
                            new UpdateWrapper<EsbServiceAtomDeploy>().eq("serviceid", serviceid).eq("instancename",app));
                    count++;
                }
            }else if(type.equals("0")) {
                EsbServiceAtomDeploy esbServiceAtomDeploy = new EsbServiceAtomDeploy();
                esbServiceAtomDeploy.setDomainname("ESBAppDomain");
                esbServiceAtomDeploy.setInstancename(app);
                esbServiceAtomDeploy.setServiceid(serviceid);
                esbServiceAtomDeploy.setStatus(status);
                esbServiceAtomDeploy.setLastupdateTime(new Date());
                esbServiceAtomDeploy.setDeploytype(deploytype);
                if(deploytype == 1) {
                    userOperationLogService.savaUserLog(request, "新增原子服务部署信息："+
                            esbAtomServiceService.selectById(serviceid).getAtomserviceCode() + " ，app：" + app);
                }else {
                    userOperationLogService.savaUserLog(request, "新增服务部署信息："+
                            esbInboundMainService.getById(serviceid).getServcode() + " ，app：" + app);
                }
                esbServiceAtomDeployService.save(esbServiceAtomDeploy);
                count++;
            }
        }
        if(count == 0) {
            return Response.error("信息无变化");
        }else {
            return Response.success("保存成功");
        }
    }

    /**
     * 服务清单：查询此条服务的服务或原子服务部署信息
     * @param serviceid 标准服务id
     * @param deploytype 部署类别：0:部署的是标准服务,1:部署的是原子服务
     * @return
     */
    @GetMapping("/selectOne")
    @ResponseBody
    @ApiOperation("服务清单：查询此条服务的服务或原子服务部署信息")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "Integer", name = "serviceid", value = "标准服务id"),
            @ApiImplicitParam(dataType = "Integer", name = "deploytype", value = "部署类别：0:部署的是标准服务,1:部署的是原子服务"),
    })
    public Response selectOne(Integer serviceid, Integer deploytype) {
        if(isEmpty(serviceid)) {
            return Response.error("请求的serviceid不能为空");
        }
        List<EsbServiceAtomDeploy> result = esbServiceAtomDeployService.list(new QueryWrapper<EsbServiceAtomDeploy>().
                eq("serviceid", serviceid).eq("deploytype",deploytype).eq("status","1"));
        return Response.success(result);
    }

}
